from Core.exception import *
from Core.models import *

import uuid


def session_update(user):
    # 生成新的 session id
    session_id = uuid.uuid4().hex
    session_info = Session(
        id=session_id,
        user=user,
        create_time=timezone.datetime.now(),
        last_visit_time=timezone.datetime.now())
    session_info.save()
    return session_id


def userinfo_update(user):
    """更新用户最后登录时间"""
    user.last_login = timezone.datetime.now()
    user.save()


def logout(request):
    if 'session_id' not in request.COOKIES:
        raise NoCookiesProvide()

    if 'user_id' not in request.COOKIES:
        raise NoCookiesProvide()

    session_id = request.COOKIES['session_id']

    session_list = Session.objects.filter(id=session_id)
    if not session_list.exists():
        raise SessionNotExist(session_id)

    # 删除session数据
    session = session_list.first()
    session.delete()


def session_verify(session_id, user_id):
    session_list = Session.objects.filter(id=session_id)
    if not session_list.exists():
        raise SessionNotExist(session_id)

    user_list = User.objects.filter(id=user_id)
    if not user_list.exists():
        raise UserNotExist(user_id)

    session = session_list.first()
    user = user_list.first()
    if session.user != user:
        raise SessionIsInvalid(session_id)


def cookie_verify(request):
    """使用Cookies验证，如果一切没问题的话则返回数据库 session 对象"""
    if 'session_id' not in request.COOKIES:
        raise NoCookiesProvide()

    if 'user_id' not in request.COOKIES:
        raise NoCookiesProvide()

    session_id = request.COOKIES['session_id']
    user_id = request.COOKIES['user_id']

    try:
        session_verify(session_id, user_id)
    except Exception as e:
        raise e
    else:
        return Session.objects.get(id=session_id)
